var express = require('express');
const db = require("../sql");
var router = express.Router();
var multiparty = require('multiparty')

/* GET home page. */
router.get('/', function (req, res, next) {
    res.render('index', {title: 'Express'});
});


// 首页数据查找
router.get('/main', function (req, res, next) {
    db.query('select * from banner', function (err, results) {
        if (err) {
            throw err
        } else if (results.length > 0) {
            let {curpage,pagesize}=req.body
            let sumpage=Math.ceil(results.length/pagesize)//返一个总页码
            // res.send({message: '获取列表成功', data, status: 200}); // 统一规定的 message
            // return;
            if(curpage==''||curpage==undefined){
                //这里是前端未传参数默认返第一页数据
                let data=results.splice(0,pagesize)//利用数组方法截取数据
                res.send({
                    sumpage:sumpage,
                    status: 200,
                    message: '获取用户基本信息成功！',
                    data: data,

                })
            }
            else {
                //这里是前端传参数返回的数据
                let data = results.splice((curpage - 1) * 4, pagesize)//利用数组方法截取数据
                res.send({
                    sumpage: sumpage,
                    status: 200,
                    message: '获取用户基本信息成功！',
                    data: data,
                })
            }
        }
    })
});

//上传图片
router.post('/addBanner', function (req, res, next) {
    var form = new multiparty.Form();
    form.uploadDir = './public/upload';
    form.parse(req, function (err, fields, files) {
        if (err) {
            console.log(err);
            var u = {"error": 1, "message": '请上传5M以图片'};
            res.end(JSON.stringify(u));
            return false;
        }
        console.log(files,fields)
        if (files.file[0].originalFilename!='') {
            var imgUrl = files.file[0].path;
            var name = files.file[0].originalFilename;
            db.query('insert into banner value(?,?,?)', [0, name, imgUrl], function (err, data) {
                if (err) throw err;
                var success = {"status": 200, "message": '上传成功', name, imgUrl};
                res.end(JSON.stringify(success));
                return
            })
        }else {
            var fail={"status": 404, "message": '未选中图片'};
            res.end(JSON.stringify(fail));
            return
        }
    })
});

//删除指定id
router.delete('/remove', function (req, res, next) {
    let id=req.query.id
    // console.log(id)
    db.query(`delete from banner where id=${id}`,function (err,data){
        if(err) throw err
        var success = {"status": 200, "message": '删除成功'};
        res.end(JSON.stringify(success));
        return
    })
});

module.exports = router;
